/**
 * Created by tiansha on 2016/4/18.
 */

import { browserHistory } from 'react-router';

const FETCH = 'employees/FETCH';
const FETCH_SUCCESS = 'employees/FETCH_SUCCESS';
const FETCH_FAIL = 'employees/FETCH_FAIL';

const CREATE = 'employees/CREATE';
const CREATE_SUCCESS = 'employees/CREATE_SUCCESS';
const CREATE_FAIL = 'employees/CREATE_FAIL';

const initialState = {
  employees: {
    content: [],
    size: 4,
    number: 0
  }
};

// Reducer

export default function employeesReducer(state = initialState, action = null) {
  switch (action.type) {
    case FETCH_SUCCESS:
      return {
        ...state,
        employees: action.result.data
      };
    case CREATE_SUCCESS:
      return {
        ...state,
      };
    default:
      return state;
  }
}

// Actions

export function fetchEmployees(pageable) {
  return  {
    types: [FETCH, FETCH_SUCCESS, FETCH_FAIL],
    promise: client => client.get('/api/employees', {params: pageable})
  };
}

export function createEmployee(data) {
  return  {
    types: [CREATE, CREATE_SUCCESS, CREATE_FAIL],
    promise: client => client.post('/rest-api/employees', data),
    afterSuccess: (dispatch, getState, response) => {
      let employees = getState().employee.employees;
      let page = Math.ceil((employees.totalElements+1)/employees.size);
      dispatch(fetchEmployees({size: employees.size, page: page-1}));
      browserHistory.push("/employees");
    }
  };
}



